<?php


namespace app\index\common;


class Rsa
{

    const  RSA_ENCRYPT_BLOCK_SIZE = 117;//加密切割长度
    const  RSA_DECRYPT_BLOCK_SIZE = 128;//解密切割长度

    /**
     * 获取私钥
     * @return bool|resource
     */
    private static function getPrivateKey()
    {
        $content = file_get_contents('/root/AliPay/cert/rsa_private_key.pem');
        return openssl_pkey_get_private($content);
    }

    /**
     * 获取公钥
     * @return bool|resource
     */
    private static function getPublicKey()
    {
        $content = file_get_contents('/root/AliPay/cert/rsa_public_key2.pem');
        return openssl_pkey_get_public($content);
    }


    /**
     * 公钥加密
     * @param string $content 加密字符串
     * @return string|null
     */
    public static function publicEncrypt($content)
    {
        if (!is_string($content)) {
            return null;
        }
        $result = '';
        $data   = str_split($content, self::RSA_ENCRYPT_BLOCK_SIZE);
        foreach ($data as $block) {
            openssl_public_encrypt($block, $dataEncrypt, self::getPublicKey(), OPENSSL_PKCS1_PADDING);
            $result .= $dataEncrypt;
        }
        return $result ? base64_encode($result) : null;
    }

    /**
     * 私钥解密
     * @param string $encrypted 解密字符串
     * @return string|null
     */
    public static function privDecrypt($encrypted)
    {
        if (!is_string($encrypted)) {
            return null;
        }
        $result = '';
        $data   = str_split(base64_decode($encrypted), self::RSA_DECRYPT_BLOCK_SIZE);
        foreach ($data as $block) {
            openssl_private_decrypt($block, $dataDecrypt, self::getPrivateKey(), OPENSSL_PKCS1_PADDING);
            $result .= $dataDecrypt;
        }
        return $result ? $result : null;
    }

}



